package api

import (
	"blog/common"
	"blog/context"
	"blog/dao"
	"blog/models"
	"blog/service"
	"blog/utils"
	"errors"
	"log"
	"net/http"
	"strconv"
	"time"
)

func (*APIHander) SaveAndUpdateAndGetPostAndDeletePost(context *context.MsContext) {
	method := context.Request.Method
	if method == http.MethodGet {
		pIdStr := context.GetPathVariable("pId")
		pid, err := strconv.Atoi(pIdStr)
		if err != nil {
			common.Error(context.W, errors.New("不识别此请求路径"))
			return
		}
		post, err := dao.GetPostById(pid)
		if err != nil {
			common.Error(context.W, err)
			return
		}
		common.Success(context.W, post)
		return
	} else {
		//获取用户id，判断用户是否登录
		token := context.Request.Header.Get("Authorization")
		_, claim, err := utils.ParseToken(token)
		if err != nil {
			common.Error(context.W, err)
			return
		}
		uid := claim.Uid
		switch method {
		case http.MethodPost:
			params := context.JsonParams
			categoryIdFloat64 := params["categoryId"].(float64)
			categoryId := int(categoryIdFloat64)
			content := params["content"].(string)
			markdown := params["markdown"].(string)
			slug := params["slug"].(string)
			title := params["title"].(string)
			postType := params["type"].(float64)
			pType := int(postType)
			post := &models.Post{
				-1,
				title,
				content,
				markdown,
				categoryId,
				uid,
				0,
				pType,
				slug,
				time.Now(),
				time.Now(),
			}
			service.SavePost(post)
			common.Success(context.W, post)
		case http.MethodPut:
			params := context.JsonParams
			categoryIdFloat64 := params["categoryId"].(float64)
			categoryId := int(categoryIdFloat64)
			content := params["content"].(string)
			markdown := params["markdown"].(string)
			slug := params["slug"].(string)
			title := params["title"].(string)
			postType := params["type"].(float64)
			pidFloat := params["pid"].(float64)
			pType := int(postType)
			pid := int(pidFloat)
			post := &models.Post{
				pid,
				title,
				content,
				markdown,
				categoryId,
				uid,
				0,
				pType,
				slug,
				time.Now(),
				time.Now(),
			}
			service.UpdatePost(post)
			common.Success(context.W, post)
		case http.MethodDelete:
			pIdStr := context.GetPathVariable("pId")
			pid, err := strconv.Atoi(pIdStr)
			if err != nil {
				common.Error(context.W, errors.New("不识别此请求路径"))
				return
			}
			post, err := dao.DeleteFromTableAndIdNameById("blog_post", "pid", pid)
			if err != nil {
				common.Error(context.W, err)
				return
			}
			common.Success(context.W, post)
			return
		}

	}
}

func (*APIHander) SearchPost(context *context.MsContext) {
	condition, err := context.GetForm("val")
	if err != nil {
		log.Println("表单获取失败")
		common.Error(context.W, err)
	}
	searchResp := service.SearchPost(condition)
	common.Success(context.W, searchResp)
}
